import React, { PureComponent } from 'react'
import { connect } from 'dva'
import { TreeSelect, Row, Col, Card, Form, Input, Button, Popconfirm } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import AccountList from './List'
import AOEForm from './AOEForm'
import styles from './Index.less'
import settings from '@/../config/defaultSettings'

const FormItem = Form.Item
const { TreeNode } = TreeSelect

// 连接组件和store
// 把state.goods定给组件的goods
@connect(state => ({
  account: state.account,
  submitting: state.loading.effects['account/save'],
}))
@Form.create()
export default class Account extends PureComponent {
  // 组件加载完成后加载数据
  componentDidMount() {
    const { dispatch } = this.props

    dispatch({
      type: 'account/fetchDepData',
    })

    dispatch({
      type: 'account/fetchRoleData',
    })

    dispatch({
      type: 'account/fetch',
      payload: {
        currentPage: 1,
      },
    })
  }

  // 树节点选择
  onSelect = selectedKeys => {
    const { dispatch } = this.props
    const values = {
      deptId: selectedKeys[0],
    }
    dispatch({
      type: 'account/fetchUser',
      payload: values,
    })
  }

  // 重置事件
  handleFormReset = () => {
    const { form, dispatch, formValues } = this.props
    form.resetFields()
    dispatch({
      type: 'account/fetch',
      payload: {
        currentPage: 1,
        ...formValues,
      },
    })
  }

  // 解锁/锁定
  handleLockSwitch = status => {
    const {
      account: { selectedRowKeys },
    } = this.props
    this.props.dispatch({
      type: 'account/lockSwitch',
      payload: {
        param: selectedRowKeys,
        status,
      },
    })
  }

  // 批量删除
  handleRemoveClick = () => {
    const {
      dispatch,
      account: { selectedRowKeys },
    } = this.props
    if (!selectedRowKeys) return

    dispatch({
      type: 'account/remove',
      payload: {
        param: selectedRowKeys,
      },
    })
  }

  // 搜索事件
  handleSearch = e => {
    e.preventDefault()

    const { dispatch, form } = this.props
    // 表单验证
    form.validateFields((err, fieldsValue) => {
      if (err) return

      const values = {
        currentPage: 1,
        ...fieldsValue,
      }
      dispatch({
        type: 'account/fetch',
        payload: values,
      })
    })
  }

  // 新增窗口
  handleModalVisible = () => {
    const { dispatch } = this.props
    dispatch({
      type: 'account/updateState',
      payload: {
        modalType: 'create',
        currentItem: {},
      },
    })
  }

  // 渲染树节点
  renderTreeNodes(data) {
    return data
      .map(item => {
        if (item.status === '0001') {
          if (item.children) {
            return (
              // 此处查询用 id
              <TreeNode title={item.name} key={item.id} value={item.id}>
                {this.renderTreeNodes(item.children)}
              </TreeNode>
            )
          }
          return <TreeNode title={item.name} key={item.id} value={item.id} />
        }
        return null
      })
      .filter(item => item || false)
  }

  // 左侧树
  // renderCategoryTree() {
  //   const { orgData } = this.props.account
  //   return (
  //     <Card
  //       type="inner"
  //       className={styles.leftTree}
  //       title={
  //         <div>
  //           <Icon type="tags" />
  //           &nbsp;归属部门
  //         </div>
  //       }
  //       extra={
  //         <Button type="primary" size="small" onClick={() => this.handleFormReset()}>
  //           全部
  //         </Button>
  //       }
  //     >
  //       <Tree showLine onSelect={this.onSelect}>
  //         {this.renderTreeNodes(orgData)}
  //       </Tree>
  //     </Card>
  //   )
  // }

  renderLeftBtn() {
    const { selectedRowKeys } = this.props.account

    return (
      <div>
        <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true, 'create')}>
          新增用户
        </Button>
        {selectedRowKeys.length > 0 && (
          <Button
            icon="lock"
            type="danger"
            style={{ marginLeft: 8 }}
            onClick={() => this.handleLockSwitch('0000')}
          >
            锁定
          </Button>
        )}
        {selectedRowKeys.length > 0 && (
          <Button
            icon="unlock"
            type="danger"
            style={{ marginLeft: 8 }}
            onClick={() => this.handleLockSwitch('0001')}
          >
            解锁
          </Button>
        )}
        {selectedRowKeys.length > 0 && (
          <span>
            <Popconfirm
              title="确定要删除所选用户吗?"
              placement="top"
              onConfirm={this.handleRemoveClick}
            >
              <Button style={{ marginLeft: 8 }} type="danger" icon="remove">
                删除用户
              </Button>
            </Popconfirm>
          </span>
        )}
      </div>
    )
  }

  renderRightBtn() {
    return (
      <div>
        <Button type="primary" htmlType="submit">
          查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
          重置
        </Button>
      </div>
    )
  }

  // 简单搜索条件
  renderSimpleForm() {
    const { depData } = this.props.account
    const { getFieldDecorator } = this.props.form
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} className={styles.margin24}>
          <Col md={8} sm={24}>
            <FormItem label="手机号码">
              {getFieldDecorator('mobile')(
                <Input
                  id="account-search"
                  placeholder="输入手机号码搜索"
                  maxLength={settings.inputMaxLength}
                />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="姓名">
              {getFieldDecorator('realityName')(
                <Input
                  id="account-name-search"
                  placeholder="输入用户名称搜索"
                  maxLength={settings.inputMaxLength}
                />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="邮箱">
              {getFieldDecorator('email')(
                <Input
                  id="account-phone-search"
                  placeholder="输入邮箱搜索"
                  maxLength={settings.inputMaxLength}
                />,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} className={styles.margin24}>
          <Col md={12} sm={24}>
            <FormItem label="所属部门">
              {getFieldDecorator('wxpartId')(
                <TreeSelect
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  showCheckedStrategy={TreeSelect.SHOW_ALL}
                  allowClear
                  showSearch
                  treeNodeFilterProp="title"
                  placeholder="请选择所属部门节点"
                >
                  {this.renderTreeNodes(depData)}
                </TreeSelect>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Card
          bordered={false}
          className={styles.noPadding}
          title={this.renderLeftBtn()}
          extra={this.renderRightBtn()}
        />
      </Form>
    )
  }

  // 渲染界面
  render() {
    const { dispatch, submitting } = this.props

    const {
      loading,
      list,
      pagination,
      selectedRowKeys,
      depData,
      roleData,
      modalType,
      currentItem,
    } = this.props.account

    const listPops = {
      dispatch,
      loading,
      list,
      pagination,
      selectedRowKeys,
    }

    const modalProps = {
      item: modalType === 'create' ? {} : currentItem,
      submitting,
      depData,
      roleData,
      modalType,
      dispatch,
      maskClosable: false,
      title: `${modalType === 'create' ? '新增用户' : '编辑用户'}`,
    }
    return (
      <PageHeaderWrapper title="用户信息管理">
        <Row gutter={24} type="flex" justify="space-around">
          {/* 左侧树 */}
          {/* <Col xl={6} lg={6} md={6} sm={6} xs={6} className={styles.fullHeightCol}>
            {this.renderCategoryTree()}
          </Col> */}
          {/* 右侧列表 */}
          <Col xl={24} lg={24} md={24} sm={24} xs={24}>
            <Card bordered={false} className={styles.noPadding}>
              <div className={styles.goodsInfoList}>
                <div className={styles.goodsInfoListForm}>{this.renderSimpleForm()}</div>
                <AccountList {...listPops} />
              </div>
            </Card>
          </Col>
        </Row>
        {/* 新增窗口 */}
        {modalType !== '' && <AOEForm {...modalProps} />}
      </PageHeaderWrapper>
    )
  }
}
